package cn.yfxu.server.task;

import cn.yfxu.server.pojo.Employee;
import cn.yfxu.server.pojo.MailConstants;
import cn.yfxu.server.pojo.MailLog;
import cn.yfxu.server.service.IEmployeeService;
import cn.yfxu.server.service.IMailLogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
* @author Xxxxyf
* @date 2021/3/12
* @desc 邮件发送定时任务
*/
@Component
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //邮件发送定时任务 10s执行一次
//    @Scheduled(cron = "0 */10 * * * ?")
//    public void mailTask(){
//        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>().eq("status", 0).lt("tryTime", new Date()));
//        list.forEach(mailLog -> {
//            //如果重试次数超过3次,更新状态为投递，不再重试
//            if (3<=mailLog.getCount()){
//                mailLogService.update(new UpdateWrapper<MailLog>().set("status",2).eq("msgId",mailLog));
//            }
//            mailLogService.update(new UpdateWrapper<MailLog>().set("count",mailLog.getCount()+1).set
//                    ("updateTime", LocalDateTime.now()).set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT)).eq("msgId",mailLog.getMsgid()));
//            Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
//            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME,employee,new CorrelationData(mailLog.getMsgid()));
//        });
//    }
}
